package classes.controller
{
	
	import flash.display.Sprite;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	import flash.system.Security;
	


	public class Connect extends Sprite
	{
		
		private var socket:Socket; 
		
		private static const HOST:String = "localhost";
		private static const PORT:int = 2021;
		
		
		public function Connect()
		{
			Security.loadPolicyFile(HOST+":"+PORT.toString(10));
			trace("소켓 통신 준비중..."); 
			
			socket = new Socket(); 
			socket.addEventListener(Event.CONNECT, onSocketConnect);
			socket.addEventListener(Event.CLOSE, onSocketClose);
			socket.addEventListener(IOErrorEvent.IO_ERROR, onSocketError );
			
			try 
			{
				socket.connect(HOST, PORT);
			}
			catch (error: IOError) 
			{
				trace("error Message "+error); 
			}
		}
		
		private function onSocketConnect(event: Event):void
		{
			trace("소켓 통신 연결.."); 
			socket.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData );
		}
		
		private function onSocketData(event:ProgressEvent):void
		{
			var msg: String = socket.readUTFBytes( socket.bytesAvailable );
			showMessage( msg );
		}
		
		private function onSocketClose(event: Event):void
		{
			trace("소켓 통신 종료...");
		}
		
		private function onSocketError(event: IOErrorEvent):void
		{
			trace("소켓 통신 에러 :" + event.errorID); 
			
		}
		
		//메세지 표시
		private function showMessage(msg:String):void
		{
			/*
			var e: EString = new EString(EString.EVENT_String, msg); 
			dispatchEvent(e);*/
			dispatchEvent(new EString(msg, EString.EVENT_String));
			
		}
		
		//전송 버튼을 누르거나 엔터를 칠경우
		public function sendMessage(msg:String):void
		{
			//msg = msg + "\n";
			if(socket && socket.connected)
			{
				socket.writeUTFBytes(msg);
				socket.flush(); 
			}
		}
		
	
	}
}